import 'dart:math';

import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/config/index.dart';
import 'package:yp/router.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/index.dart';
import 'package:yp/widgets/shop.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'dart:async';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter/cupertino.dart';

final List orderStateList = ['待付款', '待发货', '拼团中', '已发货', '待自提', '待评价', '已完成'];

// 订单
class Order extends StatefulWidget {
  const Order({Key key}) : super(key: key);

  @override
  _OrderState createState() => _OrderState();
}

class _OrderState extends State<Order> with SingleTickerProviderStateMixin {
  TabController _controller;

  var _tabList = [
    Tab(text: '全部'),
    Tab(text: '待付款'),
    Tab(text: '待配送/自提'),
    Tab(text: '待送达'),
    Tab(text: '待评价'),
  ];

  @override
  void initState() {
    super.initState();

    _controller =
        TabController(initialIndex: 0, length: _tabList.length, vsync: this);
  }

  @override
  void dispose() async {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: YPNavigationBar('全部订单',
            backgroundColor: EsColors.Primary,
            showBack: false,
            titleColor: EsColors.White),
        body: Column(
          children: [
            _tabHeadder(),
            YpLine(
              height: 20,
              thickness: 20,
              color: EsColors.BackGroundSecondary,
            ),
            _orderList(),
          ],
        ));
  }

  ///  tab栏切换的头部
  Widget _tabHeadder() {
    return Container(
      color: EsColors.White,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: ExtendedTabBar(
        tabs: List<Widget>.generate(
            _controller.length, (int index) => _tabList[index]),
        controller: _controller,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.Primary,
        isScrollable: _controller.length > 5,
        unselectedLabelColor: EsColors.TitleSecondary,
        indicatorSize: TabBarIndicatorSize.label,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        indicator: const ExtendedUnderlineTabIndicator(
            // size: 30,
            borderSide: BorderSide(color: EsColors.Primary, width: 2)),
      ),
    );
  }

  /// 下边对应的列表
  Widget _orderList() {
    return Expanded(
      child: TabBarView(
          controller: _controller,
          children: List<Widget>.generate(
              _controller.length,
              (int index) => OrderList(
                    orderState: _getOrderState(index),
                  )).toList()),
    );
  }

  /// 获取不同状态下的订单状态数组
  List<int> _getOrderState(int type) {
    switch (type) {
      case 0:
        return [];
        break;
      case 1:
        return [0];
        break;
      case 2:
        return [1, 2, 4];
        break;
      case 3:
        return [3];
        break;
      case 4:
        return [5];
        break;
      default:
        return [0];
        break;
    }
  }
}

class OrderList extends StatefulWidget {
  /// 能够获取的数组  item状态随机
  final List<int> orderState;

  const OrderList({Key key, this.orderState}) : super(key: key);
  @override
  _OrderListState createState() => _OrderListState();
}

class _OrderListState extends State<OrderList>
    with AutomaticKeepAliveClientMixin {
  List<Map<String, dynamic>> _orderInfoList = [];

  final _isHours = true;
  bool _star = false;

  final StopWatchTimer _stopWatchTimerDown = StopWatchTimer(
    mode: StopWatchMode.countDown,
    presetMillisecond: StopWatchTimer.getMilliSecFromSecond(3),
    onChange: (value) => print('onChange $value'),
    onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
    onChangeRawMinute: (value) => print('onChangeRawMinute $value'),
    onEnded: () {
      print('onEnded');
    },
  );
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000), () {
      _orderInfoList = [
        {
          'shopName': '长风公园大悦城店',
          'shopState': '预售',
          'orderState': 1,
          'amount': '11.00',
          'num': 5
        },
        {
          'shopName': '嘉定安亭贾婷店',
          'shopState': '',
          'orderState': 2,
          'amount': '200.23',
          'num': 2
        },
        {
          'shopName': '南京东路步行街店',
          'shopState': '拼团',
          'orderState': 3,
          'amount': '300.45',
          'num': 4
        },
        {
          'shopName': '大润发旗舰店',
          'shopState': '',
          'orderState': 4,
          'amount': '400.56',
          'num': 1
        },
        {
          'shopName': '地铁站附近的店',
          'shopState': '',
          'orderState': 5,
          'amount': '600.22',
          'num': 2
        },
        {
          'shopName': '奈雪的茶',
          'shopState': '',
          'orderState': 6,
          'amount': '2.45',
          'num': 3
        },
        {
          'shopName': '喜茶',
          'shopState': '',
          'orderState': 0,
          'amount': '90.23',
          'num': 4
        },
      ];
    }).whenComplete(() {
      if (mounted) {
        _refreshController.refreshCompleted();
        setState(() {});
      }
    });
  }

  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 1000), () {
      _orderInfoList.addAll([
        {
          'shopName': '长风公园大悦城店',
          'shopState': '预售',
          'orderState': 1,
          'amount': '11.00',
          'num': 5
        },
        {
          'shopName': '嘉定安亭贾婷店',
          'shopState': '',
          'orderState': 2,
          'amount': '200.23',
          'num': 2
        },
        {
          'shopName': '南京东路步行街店',
          'shopState': '拼团',
          'orderState': 3,
          'amount': '300.45',
          'num': 4
        },
        {
          'shopName': '大润发旗舰店',
          'shopState': '',
          'orderState': 4,
          'amount': '400.56',
          'num': 1
        },
        {
          'shopName': '地铁站附近的店',
          'shopState': '',
          'orderState': 5,
          'amount': '600.22',
          'num': 2
        },
        {
          'shopName': '奈雪的茶',
          'shopState': '',
          'orderState': 6,
          'amount': '2.45',
          'num': 3
        },
        {
          'shopName': '喜茶',
          'shopState': '',
          'orderState': 6,
          'amount': '90.23',
          'num': 4
        },
      ]);
    }).whenComplete(() {
      if (mounted) {
        _refreshController.loadComplete();
      }
      setState(() {});
    });
  }

  @override
  void initState() {
    super.initState();
    _stopWatchTimerDown.rawTime.listen((value) =>
        print('rawTime $value ${StopWatchTimer.getDisplayTime(value)}'));
    _stopWatchTimerDown.minuteTime
        .listen((value) => print('minuteTime $value'));
    _stopWatchTimerDown.secondTime
        .listen((value) => print('secondTime $value'));
    _stopWatchTimerDown.records.listen((value) => print('records $value'));

    _stopWatchTimerDown.setPresetHoursTime(11);
    _stopWatchTimerDown.setPresetMinuteTime(20);
    _stopWatchTimerDown.setPresetSecondTime(12);

    /// Can be set preset time. This case is "00:01.23".
    // _stopWatchTimerDown.setPresetTime(mSec: 1234);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: ClassicHeader(),
        footer: ClassicFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
            itemBuilder: (context, index) {
              return _orderItem(_orderInfoList[index]);
            },
            separatorBuilder: (context, index) => YpLine(
                height: 20, thickness: 20, color: EsColors.BackGroundSecondary),
            itemCount: _orderInfoList.length),
      ),
    );
  }

  /// 订单item
  Widget _orderItem(Map<String, dynamic> info) {
    return GestureDetector(
      onTap: () {
        /// 查看商品详情
        Get.toNamed(RouteConfig.orderDetail);
      },
      child: Container(
        color: EsColors.White,
        padding: const EdgeInsets.only(bottom: 14),
        child: Column(
          children: [
            ShopName(
              info['shopName'],
              shopState: info['shopState'],
              orderState: orderStateList[widget.orderState.length == 0
                  ? (info['orderState'])
                  : widget.orderState[_random()]],
            ),
            YpLine(),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                print('查看购买商品');
              },
              child: Container(
                margin:
                    const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
                child: Row(
                  children: [
                    Expanded(
                        child: Wrap(
                      spacing: 6,
                      children: List.generate(
                          info['num'] > 5 ? 5 : info['num'],
                          (index) => CachedImage(
                                width: (MediaQuery.of(context).size.width / 7),
                                height: MediaQuery.of(context).size.width / 7,
                                path:
                                    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbdn.135editor.com%2Ffiles%2Fusers%2F73%2F738683%2F201810%2FBfIVpTUH_SnJY.gif&refer=http%3A%2F%2Fbdn.135editor.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633256466&t=956aa5d483eaf297e5a68e5e97321390',
                                border: Border.all(
                                    color: EsColors.BackGroundSecondary,
                                    width: 1),
                              )),
                    )),
                    // SizedBox(width: 8),
                    Text(
                      '共' +
                          (info['num'] > 5 ? 5 : info['num']).toString() +
                          '件',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: EsColors.ContentSecondary,
                          fontSize: EsSizes.SM,
                          fontWeight: EsFontWeights.Normal),
                    )
                  ],
                ),
              ),
            ),
            Row(
              children: [
                SizedBox(width: 12),
                RichText(
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  text: TextSpan(
                      text: '实付：￥',
                      style: TextStyle(
                          fontSize: EsSizes.XS,
                          color: EsColors.TitleSecondary,
                          fontWeight: EsFontWeights.Normal),
                      children: <TextSpan>[
                        TextSpan(
                            text: info['amount'],
                            style: TextStyle(
                                fontSize: EsSizes.LG,
                                color: EsColors.TitleSecondary,
                                fontWeight: EsFontWeights.Medium)),
                      ]),
                ),
                Expanded(child: SizedBox()),
                Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: _orderProgress(widget.orderState.length == 0
                      ? info['orderState']
                      : widget.orderState[_random()]),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 订单进度 不同状态下的右下角按钮
  Widget _orderProgress(int status) {
    switch (status) {

      /// 待付款
      case 0:
        return _timer();
        break;

      /// 待发货
      case 1:
        return EsOutLineButton(
          '再来一单',
          onTap: () {
            print('再来一单');
          },
        );
        break;

      /// 拼团中
      case 2:
        return Row(
          children: [
            EsOutLineButton(
              '订单详情',
              normal: true,
              onTap: () {
                print('订单详情');
              },
            ),
            SizedBox(width: 12.w),
            EsOutLineButton(
              '拼团详情',
              onTap: () {
                print('拼团详情');
              },
            ),
          ],
        );
        break;

      /// 已发货
      case 3:
        return Row(
          children: [
            EsOutLineButton(
              '查看物流',
              normal: true,
              onTap: () {
                print('查看物流');
              },
            ),
            SizedBox(width: 12.w),
            EsOutLineButton(
              '再来一单',
              onTap: () {
                print('再来一单');
              },
            ),
            SizedBox(width: 12.w),
            EsOutLineButton(
              '确认收货',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                print('确认收货');
              },
            ),
          ],
        );
        break;

      /// 待自提
      case 4:
        return RichText(
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          text: TextSpan(
              text: '自提码：',
              style: TextStyle(
                  fontSize: EsSizes.XS,
                  color: EsColors.TitleSecondary,
                  fontWeight: EsFontWeights.Normal),
              children: <TextSpan>[
                TextSpan(
                    text: '444',
                    style: TextStyle(
                        fontSize: EsSizes.LG,
                        color: EsColors.TitleSecondary,
                        fontWeight: EsFontWeights.Medium)),
              ]),
        );
        break;

      /// 待评价
      case 5:
        return Row(
          children: [
            EsOutLineButton(
              '再来一单',
              onTap: () {
                print('再来一单');
              },
            ),
            SizedBox(width: 12.w),
            EsOutLineButton(
              '晒单评价',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                print('晒单评价');
              },
            ),
          ],
        );
        break;

      /// 已完成
      case 6:
        return Row(
          children: [
            EsOutLineButton(
              '开具发票',
              normal: true,
              onTap: () {
                print('再来一单');
              },
            ),
            SizedBox(width: 12.w),
            EsOutLineButton(
              '再来一单',
              onTap: () {
                print('再来一单');
              },
            ),
          ],
        );
        break;
      default:
        return SizedBox();
    }
  }

  ///  倒计时
  Widget _timer() {
    /// Display stop watch time
    _stopWatchTimerDown.setPresetTime(mSec: 12341111);
    return GestureDetector(
      onTap: () {
        print('点击开启 关闭倒计时');
        setState(() {
          _star = !_star;
          _stopWatchTimerDown.onExecute
              .add(_star ? StopWatchExecute.start : StopWatchExecute.stop);
        });
      },
      child: StreamBuilder<int>(
        stream: _stopWatchTimerDown.rawTime,
        initialData: _stopWatchTimerDown.rawTime.value,
        builder: (context, snap) {
          final value = snap.data;
          final displayTime = StopWatchTimer.getDisplayTime(value,
              hours: _isHours, milliSecond: false);
          return Container(
            decoration: BoxDecoration(
                color: EsColors.Primary,
                borderRadius: BorderRadius.circular(20.0)),
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            child: Text(
              '去付款' + displayTime,
              style: const TextStyle(
                  fontSize: EsSizes.SM,
                  color: EsColors.White,
                  fontWeight: EsFontWeights.Normal),
            ),
          );
        },
      ),
    );
  }

  int _random() {
    return Random().nextInt(widget.orderState.length);
  }

  @override
  void dispose() async {
    super.dispose();
    _refreshController.dispose();
    await _stopWatchTimerDown.dispose();
    print('dispose Finish');
  }

  @override
  bool get wantKeepAlive => true;
}
